package com.dex4d.ui.wallet.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.dex4d.R;
import com.dex4d.core.AppToolBarBaseActivity;
import com.dex4d.model.User;
import com.dex4d.utils.ImgUtils;
import com.king.zxing.util.CodeUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.PermissionRequest;

/**
 * Created by chengyuchun on 2018/10/24.
 */
public class WalletReceiveActivity extends AppToolBarBaseActivity implements EasyPermissions.PermissionCallbacks{

    @BindView(R.id.img_qr_code)
    protected ImageView mImgQrCode;

    @BindView(R.id.tv_receive_address)
    protected TextView tv_receive_address;

    @BindView(R.id.tv_save_image)
    TextView tv_save_image;

    private static final String[] READ_AND_WRITE_STORAGE =
            {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static final int RC_READ_AND_WRITE_STORAGE = 101; //request code

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, WalletReceiveActivity.class);
        activity.startActivity(intent);
    }
    @Override
    protected void initToolbar() {
        showBackView();
        showTitle(getString(R.string.receive));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_wallet_receive;
    }

    @Override
    protected void initVariables() {
        tv_save_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveImage();
            }
        });

        mImgQrCode.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showPopWindow();
                return true;
            }
        });
    }

    @Override
    protected void loadData() {
        Bitmap bitmap = CodeUtils.createQRCode(User.getInstance().getAddress(), getScreenWidth()/2);
        mImgQrCode.setImageBitmap(bitmap);
        tv_receive_address.setText(User.getInstance().getAddress());
    }

    @OnClick(R.id.btn_copy)
    public void onViewClick(){
        copyAddress();
        Toast.makeText(this, R.string.copy_address_remind, Toast.LENGTH_LONG).show();
    }

    private void copyAddress() {
        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newPlainText("Label", tv_receive_address.getText().toString());
        clipboardManager.setPrimaryClip(mClipData);
    }

    protected int getScreenWidth() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    /**
     * 保存图片
     */
    @AfterPermissionGranted(RC_READ_AND_WRITE_STORAGE)
    private void saveImage() {
        if (hasReadAndWritePermissions()) {
            mImgQrCode.setDrawingCacheEnabled(true);
            Bitmap bitmap = mImgQrCode.getDrawingCache();
            boolean isSaveSuccess = ImgUtils.saveImageToGallery(this, bitmap);
            mImgQrCode.setDrawingCacheEnabled(false);
            if (isSaveSuccess) {
                Toast.makeText(this,getString(R.string.save_image_success),Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this,getString(R.string.save_image_failure),Toast.LENGTH_SHORT).show();
            }
        } else {
            // Ask for one permission
//            EasyPermissions.requestPermissions(
//                    this,
//                    null,
//                    RC_READ_AND_WRITE_STORAGE,
//                    READ_AND_WRITE_STORAGE);

            EasyPermissions.requestPermissions(
                    new PermissionRequest.Builder(this, RC_READ_AND_WRITE_STORAGE, READ_AND_WRITE_STORAGE)
                            .setRationale(R.string.permission_storage)
                            .setPositiveButtonText(R.string.rationale_ask_ok)
                            .setNegativeButtonText(R.string.rationale_ask_cancel)
                            .setTheme(R.style.Theme_AppCompat)
                            .build());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
//        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
//        }
    }

    /**
     * 判断是否有读写文件夹权限
     *
     * @return
     */
    private boolean hasReadAndWritePermissions() {
        return EasyPermissions.hasPermissions(this, READ_AND_WRITE_STORAGE);
    }

    private void showPopWindow() {
        setBackgroundAlpha(0.3823f);//设置屏幕透明度

        View contentView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.save_image_popupwindow, null);
        final PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT,true);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                setBackgroundAlpha(1.0f);
            }
        });

        Button btn_save_image = contentView.findViewById(R.id.btn_save_image);
        Button btn_cancel = contentView.findViewById(R.id.btn_cancel);
        btn_save_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveImage();
                popupWindow.dismiss();
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        View rootView = findViewById(R.id.root_view); // 當前頁面的根佈局
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM | Gravity.CENTER, 0, 0);
    }

    /** * 设置添加屏幕的背景透明度 * */
    private void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }
}
